﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SS.LNDX.Service.Core.Model;
using SS.LNDX.Service.Core.Provider;
using Dapper;
using System.Data.SqlClient;
using SiteServer.Plugin;

namespace SS.LNDX.Service.Controllers
{
    [RoutePrefix("enrollment")]
    public class EnrollmentController : ApiController
    {
        private const string Route = "";
        public static SqlConnection conn => new SqlConnection(SiteServer.Plugin.Context.ConnectionString);

        [HttpPost, Route(Route)]
        public IHttpActionResult Create(dynamic jsonModel)
        {
            try
            {
                var enrollment = new Enrollment();
                enrollment.ContentId = jsonModel.contentId;
                enrollment.UserId = jsonModel.userId;
                enrollment.State = 0;

                dynamic content = ContentDao.GetModel(enrollment.ContentId);
                if(content.RemainCount != 0)
                {
                    var id = EnrollmentDao.Insert(enrollment);
                    return Ok(new { value = id });
                }
                else
                {
                    return BadRequest("课程报名人数已满");
                }

                
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost, Route("delete/{id}")]
        public IHttpActionResult Delete([FromUri]int id)
        {
            try {
                EnrollmentDao.Delete(id);
                return Ok("success");
            } catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("{userId}/{parentId}")]
        public IHttpActionResult GetValidEnrollmentOfUser([FromUri]int userId, [FromUri]int parentId)
        {
            try
            {
                string sql = $"SELECT * FROM ss_lndx_EnrollmentDetails WHERE IsChecked='True' AND UserId={userId} and ParentId={parentId}";
                var result = new { value = conn.Query<dynamic>(sql) };
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("history/{userId}")]
        public IHttpActionResult GetInvalidEnrollmentOfUser([FromUri]int userId)
        {
            try
            {
                string sql = $"SELECT * FROM ss_lndx_EnrollmentDetails WHERE IsChecked='False' AND CheckedLevel=-1 AND UserId={userId}";
                var result = new { value = conn.Query<dynamic>(sql) };
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("{id}")]
        public IHttpActionResult Get(int id)
        {
            try
            {
                string sql = $"SELECT * FROM ss_lndx_EnrollmentDetails WHERE Id={id}";
                var result = new { value = conn.Query<dynamic>(sql) };
                return Ok(result);
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("search")]
        public IHttpActionResult Search()
        {
            var request = Context.GetCurrentRequest();
            //var siteId = request.GetQueryInt("siteId");
            string where = request.GetQueryString("where");
            string key = request.GetQueryString("key");
            string keyword = request.GetQueryString("keyword");
            string sortExpression = string.IsNullOrEmpty(request.GetQueryString("sort"))?"Id DESC" : request.GetQueryString("sort");

            //string whereExpression = $@"SiteId={siteId}";
            string whereExpression = "1=1";

            if (key == "user")
            {
                whereExpression += $@" AND DisplayName Like '%{keyword}%'";
            }
            if (key == "id")
            {
                whereExpression += $@" AND UserId = {keyword}";
            }
            if (!string.IsNullOrEmpty(where))
            {
                whereExpression += where;
            }

            string sqlContent = $"SELECT * FROM ss_lndx_EnrollmentDetails WHERE {whereExpression} ORDER BY {sortExpression}";
            string sqlCount = $"SELECT COUNT(*) FROM ss_lndx_EnrollmentDetails WHERE {whereExpression}";

            return Ok(new { count = conn.QuerySingle<int>(sqlCount), result = conn.Query<dynamic>(sqlContent) });
        }

        [HttpGet, Route("count")]
        public IHttpActionResult GetCount()
        {
            var request = Context.GetCurrentRequest();
            string category = request.GetQueryString("category");

            string sql = "";

            if(category == "all")
            {
                sql = $"SELECT SUM(EnrollmentCount) FROM ss_lndx_EnrollmentCountByContent";
            }
            
            return Ok(new { count = conn.QuerySingle<int>(sql) });
        }

        [HttpGet, Route("bycontents")]
        public IHttpActionResult GetEnrollmentsOfContents()
        {
            try
            {
                var request = Context.GetCurrentRequest();
                string strIds = request.GetQueryString("ids");

                var ids = strIds.Split(new char[] { '-' });

                string sql = "";
                List<dynamic> results = new List<dynamic>();

                foreach (var id in ids)
                {
                    sql = $@"SELECT * FROM ss_lndx_EnrollmentDetails WHERE ContentId = {id}";
                    results.Add(new { enrollments = conn.Query<dynamic>(sql) });
                }

                return Ok(new { result = results });
            }
            catch (Exception ex)
            {

                return InternalServerError(ex);
            }
        }

        [HttpPost, Route("import")]
        public IHttpActionResult CopyEnrollments([FromUri]int targetId, [FromUri]int sourceId)
        {
            try
            {
                var request = Context.GetCurrentRequest();
                string sql = "";
                sql = $@"INSERT INTO ss_lndx_Enrollment(ContentId, UserId, [State]) SELECT {targetId.ToString()}, UserId, [State] FROM ss_lndx_Enrollment WHERE ContentId = {sourceId.ToString()}";

                return Ok(new { result = "success", count = conn.Execute(sql) });
            }
            catch (Exception ex)
            {

                return InternalServerError(ex);
            }
        }

    }
}
